package cn.rxmind.dlicense.server.dto;

import cn.hutool.core.bean.BeanUtil;
import cn.rxmind.dlicense.core.base.DLicenseContent;
import cn.rxmind.dlicense.core.constants.CheckRuleEnum;
import cn.rxmind.dlicense.core.rule.IpRule;
import cn.rxmind.dlicense.core.rule.MacRule;
import cn.rxmind.dlicense.core.rule.SpringApplicationNameRule;
import cn.rxmind.dlicense.core.utils.AssertUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 创建证书参数
 *
 * @author renxin
 * @email renxinzhiliangzhi@163.com
 * @date 2021/4/14 10:50 上午
 */
@NoArgsConstructor
@AllArgsConstructor
@Data
@ApiModel(value = "证书创建参数",description = "证书创建参数")
public class CreateLicenseDTO {

    @ApiModelProperty("选择的校验规则")
    private Set<CheckRuleEnum> activeRules;
    @ApiModelProperty("证书有效时间段")
    private ActiveTimeRuleDTO licenseActiveTimeRule;
    @ApiModelProperty("IP规则")
    private IncludeAndExcludeRuleDTO<String> ipRule;
    @ApiModelProperty("mac规则")
    private IncludeAndExcludeRuleDTO<String> macRule;
    @ApiModelProperty("子站编码规则")
    private IncludeAndExcludeRuleDTO<String> springApplicationNameRule;
    @ApiModelProperty("自定义扩展参数")
    private Map<String, Object> customContent;

    public void check(){

        AssertUtil.assertFalse(Objects.isNull(activeRules) || activeRules.isEmpty(),"激活规则未配置");
        AssertUtil.assertFalse(Objects.isNull(licenseActiveTimeRule),"证书有效期规则未配置");
        AssertUtil.assertFalse(this.activeRules.contains(CheckRuleEnum.IP_ADDRESSES) && Objects.isNull(ipRule),"IP规则未配置");
        AssertUtil.assertFalse(this.activeRules.contains(CheckRuleEnum.MAC_ADDRESSES) && Objects.isNull(macRule),"Mac规则未配置");
        AssertUtil.assertFalse(this.activeRules.contains(CheckRuleEnum.SPRING_APPLICATION_NAME) && Objects.isNull(springApplicationNameRule),"子站编码规则未配置");
    }

    public DLicenseContent covert2UtryLicenseContent(){
        DLicenseContent content = new DLicenseContent();
        if(this.activeRules != null) {
            content.getActiveRules().addAll(activeRules);
        }
        if(this.licenseActiveTimeRule != null) {
            content.setLicenseActiveTimeRule(this.licenseActiveTimeRule.covert2ActiveTimeRule());
        }

        content.setIpRule(BeanUtil.toBean(this.ipRule, IpRule.class));
        content.setMacRule(BeanUtil.toBean(this.macRule, MacRule.class));
        content.setSpringApplicationNameRule(BeanUtil.toBean(this.springApplicationNameRule, SpringApplicationNameRule.class));

        content.setCustomContent(this.customContent);

        return content;
    }


}
